package org.richin.net.util;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.richin.lang.util.RandomUtil;

public class PageStatic {
	public  void convert2Html(String sFilePath,String sSavePath,String sHtmlFile) throws IOException
	{
		PageStatic ru = new PageStatic(); 
		String baseHref="<base href='"+sFilePath+"'></base>";
	/*	String filePath = ru.getClass().getResource("").getPath().toString(); //取得项目根目录
		filePath = filePath.substring(1, filePath.indexOf("WEB-INF")); 
	*/
		String filePath="D:\\web\\";
		int HttpResult; 
		String SavePath = filePath + sSavePath; //保存路径 
		URL url=new URL(sFilePath); 
		URLConnection urlconn=url.openConnection(); //抽象类 URLConnection 是所有类的超类，它代表应用程序和 URL 之间的通信链接，通过在 URL 上调用 openConnection 方法创建连接对象 
		urlconn.addRequestProperty("Accept-Language", "zh-cn");
		urlconn.connect(); //使用 connect 方法建立到远程对象的实际连接 
		HttpURLConnection httpconn=(HttpURLConnection)urlconn; //每个 HttpURLConnection 实例都可用于生成单个请求，但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络 

		HttpResult=httpconn.getResponseCode(); //getResponseCode可以从 HTTP 响应消息获取状态码 

		if(HttpResult!=HttpURLConnection.HTTP_OK) { 
		} else { 
			String charType=httpconn.getContentType();
			System.out.println("初始编码:"+charType);
			charType=getEncdoer(charType);
			System.out.println("第一次编码:"+charType);
			if(StringUtils.equals("GB2312", charType))
			{
				System.out.println(httpconn.getInputStream().markSupported());
				charType=getEncdoer(IOUtils.toString(httpconn.getInputStream()));
			}
				
			System.out.println("最终编码:"+charType);
			HttpURLConnection connection=(HttpURLConnection)new URL(sFilePath).openConnection();
			connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)");
		InputStreamReader isr = new InputStreamReader(connection.getInputStream(),charType); 

		BufferedReader in = new BufferedReader(isr); 
		String inputLine; 
		if(!SavePath.endsWith("/")) { 
		SavePath+="/"; 
		} 
		FileOutputStream fout = new FileOutputStream(SavePath+sHtmlFile); 
		
		StringBuilder sb=new StringBuilder();
		while ((inputLine = in.readLine())!= null) 
		{ 
		     if(inputLine.toLowerCase().equals("<head>"))   
		         inputLine=inputLine+System.getProperty("line.separator")+baseHref;//加入basehref   
		         inputLine=inputLine+System.getProperty("line.separator");  //换行   
		         fout.write(inputLine.getBytes()); 
		}
		//fout.write(sb.toString().getBytes());
		in.close(); 
		fout.close(); 
		} 

	}

	public static String getEncdoer(String string)
	{
		Pattern p=Pattern.compile("charset\\s*=\\s*([^\"]+)");
		   Matcher m=p.matcher(string);
		   if(m.find())
		return m.group(1);
		   return "GB2312";
	}
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		long star=System.currentTimeMillis();
		PageStatic pageStatic=new PageStatic();
		String string = "http://javne.javaeye.com/blog/254583";
		pageStatic.convert2Html(string,"/",RandomUtil.randomString(8)+".html");  
		long end=System.currentTimeMillis();
		System.out.println((end-star)/1000);

	}

}